/***************************************************************************
 *   Copyright (C) 2007 by Sebastian Bilski, Lance Cooper, Jeff Rebacz,
 *   									and Alex Zelenskiy
 *   sbilski@iit.edu
 *   lance.m.cooper@gmail.com
 *   jeff.rebacz@gmail.com
 *   voiceofanarchy@gmail.com
 *
 *	This file is part of connect3
 *
 *   connect3 is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License, version 2,
 *    as published by the Free Software Foundation
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc., 
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 ***************************************************************************/

import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Properties;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

/*
 * GUI_Server_Options.java
 *
 * Created on December 5, 2007, 7:21 PM
 */
public class GUI_Server_Options extends javax.swing.JDialog {
    

    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonSave;
    private javax.swing.JTextField fieldHeight;
    private javax.swing.JTextField fieldPlayerNumber;
    private javax.swing.JTextField fieldPort;
    private javax.swing.JTextField fieldTime;
    private javax.swing.JTextField fieldWidth;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField fieldMaster;
    private javax.swing.JLabel labelHeight;
    private javax.swing.JLabel labelHintHeight;
    private javax.swing.JLabel labelHintPlayer;
    private javax.swing.JLabel labelHintPort;
    private javax.swing.JLabel labelHintTime;
    private javax.swing.JLabel labelHintWidth;
    private javax.swing.JLabel labelPlayerNumber;
    private javax.swing.JLabel labelPort;
    private javax.swing.JLabel labelTime;
    private javax.swing.JLabel labelWidth;
	private javax.swing.JLabel labelHintMaster;
	private JLabel labelMaster;
	
    /** Creates new form GUI_Server_Options */
    public GUI_Server_Options(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        if(ServerController.config!=null){        	
        	
    		try {
    			ServerController.config.load(new FileInputStream("server.config"));
    		} catch (Exception e1) {
    			System.err.println("failed to load server configuration file: " + e1.getMessage());
    			System.exit(1);
    		}

    		//read values off config file, and set up accordingly
    		fieldPlayerNumber.setText(ServerController.config.getProperty("numberOfPlayers"));
    		fieldWidth.setText(ServerController.config.getProperty("gridWidth"));
    		fieldHeight.setText(ServerController.config.getProperty("gridHeight"));
    		fieldTime.setText(ServerController.config.getProperty("timeLimit"));
    		fieldPort.setText(ServerController.config.getProperty("port"));
    		fieldMaster.setText(ServerController.config.getProperty("register"));
        }
        
    }
    
    private void initComponents() {

        jTextField5 = new javax.swing.JTextField();
        labelPlayerNumber = new javax.swing.JLabel();
        labelWidth = new javax.swing.JLabel();
        labelHeight = new javax.swing.JLabel();
        labelTime = new javax.swing.JLabel();
        labelMaster = new javax.swing.JLabel();
        fieldPlayerNumber = new javax.swing.JTextField();
        fieldWidth = new javax.swing.JTextField();
        fieldHeight = new javax.swing.JTextField();
        fieldTime = new javax.swing.JTextField();
        labelPort = new javax.swing.JLabel();
        fieldPort = new javax.swing.JTextField();
        fieldMaster = new javax.swing.JTextField();
        labelHintPlayer = new javax.swing.JLabel();
        labelHintWidth = new javax.swing.JLabel();
        labelHintHeight = new javax.swing.JLabel();
        labelHintTime = new javax.swing.JLabel();
        labelHintPort = new javax.swing.JLabel();
        labelHintMaster = new javax.swing.JLabel();
        buttonSave = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();

        jTextField5.setText("jTextField5.text");
        jTextField5.setName("jTextField5");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        labelPlayerNumber.setText("maximum number of players"); // NOI18N
        labelPlayerNumber.setName("labelPlayerNumber"); // NOI18N

        labelWidth.setText("grid width:"); // NOI18N
        labelWidth.setName("labelWidth"); // NOI18N

        labelHeight.setText("grid height:"); // NOI18N
        labelHeight.setName("labelHeight"); // NOI18N

        labelTime.setText("time limit(minutes):"); // NOI18N
        labelTime.setName("labelTime"); // NOI18N
        
        labelMaster.setText("Register with master:"); // NOI18N
        labelMaster.setName("labelMaster"); // NOI18N

        fieldPlayerNumber.setText("0"); // NOI18N
        fieldPlayerNumber.setName("fieldPlayerNumber"); // NOI18N

        fieldWidth.setText("8"); // NOI18N
        fieldWidth.setName("fieldWidth"); // NOI18N

        fieldHeight.setText("6"); // NOI18N
        fieldHeight.setName("fieldHeight"); // NOI18N

        fieldTime.setText("0"); // NOI18N
        fieldTime.setName("fieldTime"); // NOI18N

        labelPort.setText("port:"); // NOI18N
        labelPort.setName("labelPort"); // NOI18N

        fieldPort.setText("6699"); // NOI18N
        fieldPort.setName("fieldPort"); // NOI18N
        
        fieldMaster.setText("0"); // NOI18N
        fieldMaster.setName("fieldMaster"); // NOI18N

        labelHintPlayer.setText("(0 for unlimited)"); // NOI18N
        labelHintPlayer.setName("labelHintPlayer"); // NOI18N

        labelHintWidth.setText("(minimum=3)"); // NOI18N
        labelHintWidth.setName("labelHintWidth"); // NOI18N

        labelHintHeight.setText("(minimum=3)"); // NOI18N
        labelHintHeight.setName("labelHintHeight"); // NOI18N

        labelHintTime.setText("(0 for unlimited)"); // NOI18N
        labelHintTime.setName("labelHintTime"); // NOI18N

        labelHintPort.setText("(default=6699)"); // NOI18N
        labelHintPort.setName("labelHintPort"); // NOI18N
        
        labelHintMaster.setText("(1=register)"); // NOI18N
        labelHintMaster.setName("labelHintMaster"); // NOI18N
        
        buttonSave.setText("save"); // NOI18N
        buttonSave.setName("buttonSave"); // NOI18N

        buttonCancel.setText("cancel"); // NOI18N
        buttonCancel.setName("buttonCancel"); // NOI18N
        
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });
        

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelPlayerNumber)
                    .addComponent(labelWidth)
                    .addComponent(labelHeight)
                    .addComponent(labelTime)
                    .addComponent(labelPort)
                    .addComponent(labelMaster))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(fieldPort)
                    .addComponent(fieldTime)
                    .addComponent(fieldHeight)
                    .addComponent(fieldWidth)
                    .addComponent(fieldPlayerNumber, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                    .addComponent(fieldMaster))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelHintPlayer)
                    .addComponent(labelHintWidth)
                    .addComponent(labelHintHeight)
                    .addComponent(labelHintTime)
                    .addComponent(labelHintPort)
                    .addComponent(labelHintMaster))
                .addContainerGap(30, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(220, Short.MAX_VALUE)
                .addComponent(buttonCancel)
                .addGap(18, 18, 18)
                .addComponent(buttonSave)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelPlayerNumber)
                    .addComponent(fieldPlayerNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelHintPlayer))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelWidth)
                    .addComponent(fieldWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelHintWidth))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelHeight)
                    .addComponent(fieldHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelHintHeight))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelTime)
                    .addComponent(fieldTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelHintTime))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelPort)
                    .addComponent(fieldPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelHintPort))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelMaster)
                    .addComponent(fieldMaster, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelHintMaster))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSave)
                    .addComponent(buttonCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>
    
    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {
       //read all fields for easy reference
    	
    	int players;
    	int width;
    	int height;
    	int time;
    	int port;
    	int master;
    	
    	try{
    	players = Integer.parseInt(fieldPlayerNumber.getText());
    	width = Integer.parseInt(fieldWidth.getText());
    	height = Integer.parseInt(fieldHeight.getText());
    	time = Integer.parseInt(fieldTime.getText());
    	port = Integer.parseInt(fieldPort.getText());
    	master = Integer.parseInt(fieldMaster.getText());
    	}catch(NumberFormatException nfe){
    		JOptionPane.showMessageDialog(this,"each field must have an integer.","input error", JOptionPane.DEFAULT_OPTION);
    		return;
    	}
    	
    	String errorMessage="";
    	if(players<0){
    		errorMessage+="Number of players cannot be negative!\n";    		
    	}
    	if(width<4){
    		errorMessage+="width must be at least 3.!\n";    		
    	}
    	if(height<4){
    		errorMessage+="height must be at least 3.\n";    		
    	}
    	if(time<0){
    		errorMessage+="time cannot be negative.\n";    		
    	}
    	if(port<2||port>65535){
    		errorMessage+="The port number must be with 1 and 65535 inclusive.\n";    		
    	}
    	
    	if(!errorMessage.equals("")){
    		JOptionPane.showMessageDialog(this,errorMessage,"input error", JOptionPane.DEFAULT_OPTION);
    		return;
    	}
    	
    	//Save to config file
    	Properties config = new Properties();
    	
    	config.setProperty("numberOfPlayers", ""+players);
    	config.setProperty("gridWidth", ""+width);
    	config.setProperty("gridHeight", ""+height);
    	config.setProperty("timeLimit", ""+time);
    	config.setProperty("port", ""+port);
    	config.setProperty("register", ""+master);
    	
    	
    	try {
			config.store(new FileWriter("server.config"),"server settings");
		} catch (Exception e1) {
			System.err.println("failed to save server configuration file: " + e1.getMessage());
			System.exit(1);
		}
    	ServerController.config=config;
    	dispose();
    	
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                GUI_Server_Options dialog = new GUI_Server_Options(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    
}
